﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zdap.Common;

namespace Datav.Design.Core
{
    /// <summary>
    /// 
    /// </summary>
    public static class TreeExtensions
    {
        /// <summary>
        /// 反向递归处理树形结构（后序遍历）
        /// </summary>
        /// <typeparam name="T">树节点类型</typeparam>
        /// <param name="tree">树形结构</param>
        /// <param name="action">处理操作</param>
        public static void ProcessTreePostOrder<T>(this IEnumerable<T> tree, Action<T> action) where T : TreeBase
        {
            if (tree == null || !tree.Any()) return;

            foreach (var node in tree)
            {
                // 先处理子节点
                if (node.Children != null && node.Children.Any())
                {
                    ProcessTreePostOrder(node.Children.Cast<T>(), action);
                }
                // 然后处理当前节点
                action(node);
            }
        }

        /// <summary>
        /// 反向递归处理树形结构（带层级信息的后序遍历）
        /// </summary>
        public static void ProcessTreePostOrder<T>(this IEnumerable<T> tree, Action<T, int> action, int level = 0) where T : TreeBase
        {
            if (tree == null || !tree.Any()) return;

            foreach (var node in tree)
            {
                // 先处理子节点
                if (node.Children != null && node.Children.Any())
                {
                    ProcessTreePostOrder(node.Children.Cast<T>(), action, level + 1);
                }

                // 然后处理当前节点
                action(node, level);
            }
        }
    }
}
